const { getBookShelf,getRecentBookShelf } = require("../../network/bookshelf")
const { debounce } = require("../../utils/Tools")

const app = getApp()

Page({
  data: {
    isShow: false, // 登录弹窗 显示/隐藏 控制变量
    change_more: false,
    recentBookShelfList: [],
    companyBookShelfList: [],
    studentBookShelfList: [],
    searchList:[],
    focus: false, // 搜索框 获得焦点/失去焦点 记录变量
    inputValue: '', // 输入框内容
    timer: null, // 定时器标识
    fontSetSize: 'small', // 用户设置的字体大小（'small'：小，'middle'：中，'large'：大）
    thisPageA: 1, // 最近阅读当前页
    thisPageB: 1, // 盛和塾书架当前页
    thisPageC: 1, // 企业书架当前页
    popup_switch:false ,//弹窗
    repair_code: "", // 用户填写的邀请码
    code_msg:"" ,
    studentIndex:""
  },

  onNavigateTo(e){
    if(this.data.studentIndex == 1){
      wx.navigateTo({
        url:e.currentTarget.dataset.url
      })
    }else{
      this.setData({
        popup_switch:true
      })
    }
  
  } ,



  /**
   * 发送验证邀请码
   * @param {*} e 
   */
  handleSendInvitationCode (e) {
    let token = wx.getStorageSync('token')
    app.http({
      config: {
        url: '/api/User/bookshelf_register',
        data: {
          token,
          code:this.data.repair_code
        },
        method: 'POST'
      },
    }).then(res => {
      console.log(res.data.message , "11111111")
      this.setData({
        popup_switch: false ,
        studentIndex:1
      })
      wx.showModal({
        title: '提示',
        content: res.data.message,
        showCancel: false,
       
      })
    }).catch(err => {
      console.log(err, 'sendCompanyCodeErr')
      this.setData({
        repair_code_error: true ,
        code_msg:"验证码错误" ,
      })
    });
  },

 /**
   * 关闭邀请码弹窗
   */
  handleClosePopup () {
    this.setData({
      popup_switch: false ,
      repair_code:"" ,

    })
  },

   /**
   * 获取填写邀请码
   * @param {*} e 
   */
  getRepairCode (e) {
    this.setData({
      repair_code: e.detail.value
    })
  },

  /**
   * 获取用户基本信息并登录
   */
  onGotUserInfo(e) {
    console.log(e, 'userInfoData')
    let _this = this
    if (e.detail.errMsg == 'getUserInfo:ok') {
      wx.showLoading({
        title: '登录中'
      })
      let wx_iv = e.detail.iv
      let encryptedData = e.detail.encryptedData
      // 获取微信小程序code
      wx.login({
        success: function (res) {
          let wx_code = res.code
          // 登录
          app.http({
            config: {
              url: '/api/User/wx_login',
              data: {
                wx_iv: wx_iv,
                encryptedData: encryptedData,
                wx_code: wx_code
              },
              method: 'POST'
            },
            isAuth: false
          }).then(res => {
            console.log(res, 'loginRes')
            // 将token存储到本地缓存
            wx.setStorageSync('token', res.data.data.token)
            wx.setStorageSync('userInfo', res.data.data)
            let timer = setTimeout(time => {
              wx.hideLoading()
              clearTimeout(timer)
            }, 100)
            /**
             * 设置token在本地缓存的存储时间
             */
            let timestamp = Date.parse(new Date()) // 当前时间（即登录时间）的时间戳（毫秒）
            // let expiration = timestamp + (3 * 24 * 3600000) // 缓存3天
            let expiration = timestamp + (332666 * 1000) // token有效时间，后端告诉的
            wx.setStorageSync('expiration', expiration)
          }).catch(err => {
            console.log(err, 'loginErr')
            wx.hideLoading()
          });
        }
      })
    } else {
      console.log('用户拒绝权限')
    }
  },

  /**
   * 搜索框获取焦点
   */
  handleFocus () {
    this.setData({
      focus: true
    })
  },

  /**
   * 搜索框失去焦点
   */
  handleBlur (e) {
    let searchValue = e.detail.value
    if (!searchValue.length) {
      this.setData({
        focus: false
      })
    }
  },

  /**
   * 输入框输入内容
   */
  handleInput (e) {
    let _this = this
    // 使用防抖提高性能
    if (_this.data.timer) {
      clearTimeout(_this.data.timer)
    }
    _this.data.timer = setTimeout(() => {
      let key_work = e.detail.value
      let token = wx.getStorageSync('token')
      app.http({
        config: {
          url: '/api/User/my_bookshelf',
          data: {
            token,
            key_work
          },
          method: 'POST'
        },
        isAuth: true
      }).then(res => {
        console.log(res, 'searchListRes')
        this.setData({
          searchList: res.data.data.data
        })
      }).catch(err => {
        console.log(err, 'searchListErr')
      })
    }, 500)
  },

  /**
   * 清空输入框内容
   */
  handleClearInput () {
    this.setData({
      inputValue: '',
      focus: false
    })
  },

  // 获取 我的书架-最近阅读 列表
  _getRecentBookShelf () {
    const that = this
    let thisPageA = that.data.thisPageA
    const data = {
      page: thisPageA
    }
    getRecentBookShelf(data).then(res=>{
      console.log('getRecentBookShelfRes', res)
      const recentBookShelfList = that.data.recentBookShelfList.length > 0 ? that.data.recentBookShelfList.concat(res.data.data) : res.data.data
      that.setData({
        recentBookShelfList
      })
      const lastPage = res.data.last_page
      if (lastPage > thisPageA) {
        thisPageA = thisPageA + 1
        that.setData({
          thisPageA
        }, () => {
          that._getRecentBookShelf()
        })
      }
    }).catch(err=>{
      console.warn(err)
      if (err.data.code == 400) {
        this.setData({
          isShow: true
        })
      }
    })
  },

  // 获取 我的书架-企业书籍 列表
  _getCompanyBookShelf () {
    const that = this
    let thisPageC = that.data.thisPageC
    const data = {
      type: 1,
      page: thisPageC
    }
    getBookShelf(data).then(res=>{
      console.log('getCompanyBookShelf', res)
      const companyBookShelfList = that.data.companyBookShelfList.length > 0 ? that.data.companyBookShelfList.concat(res.data.data) : res.data.data
      that.setData({
        companyBookShelfList
      })
      const lastPage = res.data.last_page
      if (lastPage > thisPageC) {
        thisPageC = thisPageC + 1
        that.setData({
          thisPageC
        }, () => {
          that._getCompanyBookShelf()
        })
      }
    }).catch(err=>{
      console.warn(err)
      if (err.data.code == 400) {
        that.setData({
          isShow: true
        })
      }
    })
  },

  // 获取 我的书架-塾生学习 列表
  _getStudentBookShelf () {
    const that = this
    let thisPageB = that.data.thisPageB
    const data = {
      type: 2,
      page: thisPageB
    }
    getBookShelf(data).then(res=>{
      console.log('getStudentBookShelfRes', res)
      const studentBookShelfList = that.data.studentBookShelfList.length > 0 ? that.data.studentBookShelfList.concat(res.data.data) : res.data.data
      that.setData({
        studentBookShelfList ,
        studentIndex:res.data.is_register 
      })
      const lastPage = res.data.last_page
      if (lastPage > thisPageB) {
        thisPageB = thisPageB + 1
        that.setData({
          thisPageB
        }, () => {
          that._getStudentBookShelf()
        })
      }
    }).catch(err=>{
      console.warn(err)
      if (err.data.code == 400) {
        that.setData({
          isShow: true
        })
      }
    })
  },

  onChageMore(){
    if(this.data.change_more){
      this.setData({
        change_more:false
      })
    }else{
      this.setData({
        change_more:true
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onLoad(options) {
    this._getRecentBookShelf()
    this._getCompanyBookShelf()
    this._getStudentBookShelf()
    this.handleFilter = debounce(this.handleFilter)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let fontSetSize = wx.getStorageSync('fontSetSize') // 本地缓存中用户设置的字体大小
    if (fontSetSize) {
      this.setData({
        fontSetSize
      })
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading() //在标题栏中显示加载图标
    this._getRecentBookShelf()
    this._getCompanyBookShelf()
    this._getStudentBookShelf()
    // wx.hideNavigationBarLoading() //完成停止加载图标
    // wx.stopPullDownRefresh()
    // (async () => {
    //   const p = await new Promise(resolve => {
    //     setTimeout(() => resolve("hello async/await"), 1000);
    //   });
    //   console.log(p);
    // })();
  },
})